import Toast from 'tdesign-miniprogram/toast/index';
import commondUtil from '../../utils/commondUtil';
import validUtil from '../../utils/validUtil';
import SignClient from "../../api/modules/signClient";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    readonly: true,
    latestPointDatePickerVisible: false,
    workDayList: [{
        id: 1,
        text: '周一'
      },
      {
        id: 2,
        text: '周二'
      },
      {
        id: 3,
        text: '周三'
      },
      {
        id: 4,
        text: '周四'
      },
      {
        id: 5,
        text: '周五'
      },
      {
        id: 6,
        text: '周六'
      },
      {
        id: 7,
        text: '周日'
      },
    ],
    openCalendarType: '',
    calendarVisible: false,
    calendarSelectDateList: [],
    m3PasswordShowOriginalFlag: false,
    screenPasswordShowOriginalFlag: false,

    id: "",
    clientName: "",
    alias: "",
    openFlag: true,
    lastOnlineTime: "",
    createTime: "",

    m3Username: "",
    m3Password: "",
    screenPassword: "",
    emailAddr: "",
    latestPoint: "08:35",
    earlyMinute: 10,
    estimateExecMin: 3,
    dayRangeList: [1, 2, 3, 4, 5],
    ignoreDateList: [],
    specialDateList: [],

    ignoreDateNotes: '',
    specialDateNotes: '',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 建立数据通道
    const eventChannel = this.getOpenerEventChannel();
    if (typeof eventChannel?.on === 'function') {
      // 监听'delivery'事件，并获取数据包
      eventChannel.on('delivery', (param) => {
        if (!param) {
          return;
        }
        this.setData({
          readonly: !param.editFlag
        });

        const clientInfo = param.clientInfo;
        if (clientInfo == null) {
          return;
        }
        for (let key in clientInfo) {
          const value = clientInfo[key];
          if (key === 'config') {
            for (let vk in value) {
              if (this.data[vk] != null) {
                this.setData({
                  [vk]: value[vk]
                });
              }
            }
            continue;
          }
          if (this.data[key] == null) {
            continue;
          }
          this.setData({
            [key]: value
          });
        }

        this.formatDateStrNotes('ignoreDate');
        this.formatDateStrNotes('specialDate');
      });
    }
  },

  formatDateStrNotes(dateKey) {
    let dateStrList = this.data[`${dateKey}List`];
    if (commondUtil.isEmpty(dateStrList)) {
      return;
    }
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    // 过滤早于当天的日期
    dateStrList = dateStrList.filter(dateStr => commondUtil.parserDate(dateStr) > now);
    this.setData({
      [`${dateKey}List`]: dateStrList,
      [`${dateKey}Notes`]: this.dateListToString(dateStrList)
    });
  },

  showLatestPointDatePicke(e) {
    if (this.data.readonly) {
      return;
    }
    this.setData({
      latestPointDatePickerVisible: true,
    });
  },
  hideLatestPointDatePicke(e) {
    this.setData({
      latestPointDatePickerVisible: false,
    });
  },
  latestPointDatePickeConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
      latestPoint: value
    });
    this.hideLatestPointDatePicke();
  },

  saveClientInfo() {
    const clientObj = {
      id: this.data.id,
      clientName: this.data.clientName,
      alias: this.data.alias,
      openFlag: this.data.openFlag,
      config: {
        m3Username: this.data.m3Username,
        m3Password: this.data.m3Password,
        screenPassword: this.data.screenPassword,
        emailAddr: this.data.emailAddr,
        latestPoint: this.data.latestPoint,
        earlyMinute: this.data.earlyMinute,
        estimateExecMin: this.data.estimateExecMin,
        dayRangeList: this.data.dayRangeList,
        ignoreDateList: this.data.ignoreDateList,
        specialDateList: this.data.specialDateList,
      }
    };
    // 校验数据
    if (!this.validClientInfo(clientObj)) {
      return;
    }
    // 转为JSON后台才能解析
    clientObj.config = JSON.stringify(clientObj.config);
    SignClient.saveUserSignClient(clientObj).then(resp => {
      if (resp.code == 1001 || !resp.data) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: resp.message ? resp.message : '保存失败！',
          theme: 'error',
          direction: 'column',
        });
        return;
      }

      Toast({
        context: this,
        selector: '#t-toast',
        message: '保存成功！',
        theme: 'success',
        direction: 'column',
      });
      wx.navigateBack();

      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel != null) {
        eventChannel.emit('refreshSignClient');
      }
    });
  },

  /**
   * 校验客户端数据
   * @param {object} clientObj 
   */
  validClientInfo(clientObj) {
    if (!validUtil.checkMinLength(clientObj.clientName, 3) || !validUtil.isNonChinese(clientObj.clientName)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '客户端名称长度应为(3~30位)，且不能为中文',
        theme: 'warning',
        direction: 'column',
      });
      return false;
    }
    const config = clientObj.config;
    if (!validUtil.isNonChinese(config.m3Username)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: 'M3用户名必填且不能为中文',
        theme: 'warning',
        direction: 'column',
      });
      return false;
    }
    if (commondUtil.isBlank(config.m3Password)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: 'M3密码必填',
        theme: 'warning',
        direction: 'column',
      });
      return false;
    }
    if (!validUtil.isEmail(config.emailAddr)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '通知邮件格式有误！',
        theme: 'warning',
        direction: 'column',
      });
      return false;
    }
    if (commondUtil.isBlank(config.latestPoint)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '最晚签到时间必填',
        theme: 'warning',
        direction: 'column',
      });
      return false;
    }
    if (!validUtil.isNumeric(config.earlyMinute)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '最早提前签到时间必填且只能为数字',
        theme: 'warning',
        direction: 'column',
      });
      return false;
    }
    if (!validUtil.isNumeric(config.estimateExecMin)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '预计签到执行时间必填且只能为数字',
        theme: 'warning',
        direction: 'column',
      });
      return false;
    }
    if (commondUtil.isEmpty(config.dayRangeList)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '签到工作日必填',
        theme: 'warning',
        direction: 'column',
      });
      return false;
    }
    return true;
  },

  showCalendarPop(e) {
    if (this.data.readonly) {
      return;
    }
    const openCalendarType = e.currentTarget.id;
    if (commondUtil.isBlank(openCalendarType)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '日期类型为空！',
        theme: 'error',
        direction: 'column',
      });
      return;
    }
    let selectTimestampList = [];
    const dateStrList = this.data[`${openCalendarType}List`];
    if (commondUtil.isNotEmpty(dateStrList)) {
      selectTimestampList = dateStrList.map(dateStr => {
        const date = commondUtil.parserDate(dateStr);
        date.setHours(0, 0, 0, 0);
        return date.getTime();
      });
    }
    this.setData({
      calendarVisible: true,
      openCalendarType: openCalendarType,
      calendarSelectDateList: selectTimestampList
    });
  },
  calendarSelectConfirm(e) {
    const timestampList = e.detail.value;
    let dateStrList = [];
    if (commondUtil.isNotEmpty(timestampList)) {
      dateStrList = timestampList.map(timestamp => {
        return commondUtil.formatDate(timestamp, false, false);
      });
    }
    this.setData({
      [`${this.data.openCalendarType}List`]: dateStrList,
      [`${this.data.openCalendarType}Notes`]: this.dateListToString(dateStrList),
      calendarSelectDateList: []
    });
  },
  dayRangeCheckChange(e) {
    this.setData({
      dayRangeList: e.detail.value,
    });
  },
  dateListToString(dateList) {
    if (commondUtil.isEmpty(dateList)) {
      return '';
    }
    let str = '';
    dateList.forEach(dateStr => str += dateStr + "、");
    if (str.endsWith("、")) {
      str = str.substring(0, str.length - 1);
    }
    return str;
  },
  showOriginalPwd(e) {
    const fieldName = `${e.currentTarget.id}ShowOriginalFlag`;
    this.setData({
      [fieldName]: !this.data[fieldName]
    });
  },
  openFlagChange(e) {
    this.setData({
      openFlag: e.detail.value,
    });
  },

})